﻿using Common.Api.Client;
using Common.Api.Dtos;
using Cyss.TaskControl.Infrastructure;
using System.Reflection;
using Cyss.Core;
using Cyss.Core.Helper;

namespace Cyss.TaskControl
{
    /// <summary>
    /// 服务控制中心
    /// </summary>
    public class ServiceControlCenter
    {
        /// <summary>
        /// 任务集合
        /// </summary>
        public static List<TaskThreadView> Services { set; get; } = new List<TaskThreadView>();

        private static MainThread mainThread = null;

        static ServiceControlCenter()
        {
            LogHelper.WriteTextLog("asdf", "Service");
            ServiceControlCenter staticMain = new ServiceControlCenter();
            staticMain.LocaTaskThread();
            staticMain.LoadDataBaseTaskThread();
            if (mainThread == null)
            {
                mainThread = new MainThread(ServiceControlCenter.Services);
                mainThread.Start();
            }
        }

        /// <summary>
        /// 开启所有服务
        /// </summary>
        public static void StartAllService()
        {
            foreach (var task in ServiceControlCenter.Services)
            {
                task.State = true;
            }
        }

        /// <summary>
        /// 加载本地任务
        /// </summary>
        /// <returns></returns>
        private void LocaTaskThread()
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            foreach (var type in GetServiceTypes())
            {
                var enable = type.GetCustomAttribute<ServiceEnableAttribute>();
                if (enable == null) continue;
                var typeInstance = assembly.CreateInstance(type.FullName) as IService;
                TaskThreadView taskThreadView = new TaskThreadView();
                taskThreadView.TaskType = type;
                taskThreadView.ServiceName = typeInstance.ServiceName;
                taskThreadView.Interval = typeInstance.Interval;
                taskThreadView.Id = typeInstance.TaskId;
                ServiceControlCenter.Services.Add(taskThreadView);
            }
            ServiceControlCenter.Services.OrderBy(x => x.DisplayOrder);
        }

        /// <summary>
        /// 获取本地任务集合
        /// </summary>
        /// <returns></returns>
        private Type[] GetServiceTypes()
        {
            return AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes().Where(t => t.HasImplementedRawGeneric(typeof(IService))))
            .ToArray();
        }

        /// <summary>
        /// 加载数据库任务
        /// </summary>
        private async Task LoadDataBaseTaskThread()
        {
            try
            {
                var tasks = await GetDataTasks();
                var configs = await GetTaskConfigs();
                var apiServices = await GetApiServices();
                foreach (var task in tasks)
                {
                    var apiService = apiServices.FirstOrDefault(x => x.Id == task.ApiServiceId);
                    if (apiService == null) continue;
                    var service = new UrlService(apiService.BaseAddress);
                    service.TaskId = task.Id;
                    service.ServiceName = task.Name;
                    service.Url = task.Url;
                    TaskThreadView taskThreadView = new TaskThreadView();
                    taskThreadView.Counter = task.Count;
                    taskThreadView.State = task.Status;
                    taskThreadView.UrlService = service;
                    taskThreadView.ServiceName = task.Name;
                    taskThreadView.Id = task.Id;
                    taskThreadView.Config = configs.FirstOrDefault(x => x.TaskId == taskThreadView.Id);
                    if (taskThreadView.Config != null) taskThreadView.Interval = taskThreadView.Config.Interval;
                    Services.Add(taskThreadView);

                }

            }
            catch (Exception ex)
            {
                throw new Exception("加载数据库任务失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 获取数据库任务
        /// </summary>
        /// <returns></returns>
        private async Task<IEnumerable<JobModel>> GetDataTasks()
        {
            var searchModel = new Common.Api.Dtos.TaskSearchModel();
            searchModel.pageSize = int.MaxValue;
            var operateResult = await CommonClientFactory.Task.GetPageListTasks(searchModel);
            if (operateResult.IsSuccess == false)
            {
                return null;
            }
            return operateResult.Data.Data;
        }

        /// <summary>
        /// 获取api服务地址信息
        /// </summary>
        /// <returns></returns>
        private async Task<IEnumerable<ApiServiceModel>> GetApiServices()
        {
            var operateResultApiService = await CommonClientFactory.ApiService.GetApiServices();
            if (operateResultApiService.IsSuccess == false)
            {
                return null;
            }
            return operateResultApiService.Data;
        }

        /// <summary>
        /// 获取服务配置
        /// </summary>
        /// <returns></returns>
        private async Task<IEnumerable<TaskConfigModel>> GetTaskConfigs()
        {
            var operateResultConfig = await CommonClientFactory.Task.GetPageListTaskConfigs(new TaskConfigSearchModel());
            if (operateResultConfig.IsSuccess == false)
            {
                return null;
            }
            return operateResultConfig.Data.Data;
        }

    }
}
